<?php

namespace app\api\controller;

use app\api\service\UserService;
use app\model\zs\ZsBallQuizze;
use app\model\zs\ZsBallRace;
use app\model\zs\ZsBallRank;
use app\model\zs\ZsMemberMeal;
use think\facade\Request;

/**
 * 欧洲杯竞猜API
 * Class BallTeam
 * @package app\api\controller
 */
class BallTeam
{
    public function list_race()
    {
        $vipcode = Request::param('vipcode');

        $list_race = ZsBallRace::with('blueTeam', 'redTeam')
            ->order('id', 'desc')
            ->select();

        $list_race = $this->sortRace($list_race);

        $list_quiz = ZsBallQuizze::where('vipcode', $vipcode)
            ->column('*', 'race_id');

        $raceTypeRels = ZsBallRace::raceTypeRels();
        $list = $list_race->map(function ($item_race) use ($raceTypeRels, $list_quiz) {
            $curr_quiz = $list_quiz[$item_race->id] ?? null;
            $quiz_end = $curr_quiz['quiz_end'] ?? null;
            $race_end = $item_race['race_end'] ?? null;


            $blue_name = $item_race->blueTeam->name;
            $red_name = $item_race->redTeam->name;

            $quiz_end_text = $this->raceEndText($quiz_end, $blue_name, $red_name);
            $race_end_team = $this->raceEndText($race_end, $blue_name, $red_name);
            $race_end_team = $race_end_team ? ('比赛结果：' . $race_end_team) : '';
            $quiz_end_team = $quiz_end_text;
            $quiz_end_text = $quiz_end_text ? '已 猜' : '竞 猜';

            $quiz_can = !$curr_quiz;
            // 判断竞猜是否开始
            if ($quiz_can) {
                if (!$this->checkStartTime($item_race['start_time'])) {
                    $quiz_can = false;
                    $quiz_end_team = '竞猜未开始';
                }
                if (!$this->checkEndTime($item_race['end_time'])) {
                    $quiz_can = false;
                    $quiz_end_team = '竞猜已结束';
                }
            }
            return [
                'id' => $item_race->id,
                'race_type_text' => $raceTypeRels[$item_race->race_type] ?? '',
                'blue_name' => $blue_name,
                'blue_icon' => $item_race->blueTeam->icon,
                'red_name' => $red_name,
                'red_icon' => $item_race->redTeam->icon,
                'race_time_text' => $this->raceTimeText($item_race->race_time),

                'quiz_can' => $quiz_can,
                'quiz_end_text' => $quiz_end_text,
                'quiz_end_team' => $quiz_end_team,
                'quiz_integral' => $curr_quiz['integral'] ?? null,

                'race_end_team' => $race_end_team,
            ];
        });

        return jsonData(1, '成功', compact('list'));
    }

    /**
     * 检测是否已经竞猜开始时间
     */
    private function checkStartTime($start_time)
    {
        $now_str = date('Y-m-d H:i:s');
        return $now_str >= $start_time;
    }

    /**
     * 检测是否已经竞猜结束时间
     */
    private function checkEndTime($end_time)
    {
        $now_str = date('Y-m-d H:i:s');
        return $now_str <= $end_time;
    }

    /**
     * 比赛排序：
     * 1.未开始比赛的排在前面，
     * 2.已经比赛的排在后面。
     */
    private function sortRace($list_race)
    {
        $now_str = date('Y-m-d H:i:s');
        $list_wait = $list_race->filter(function ($item_race) use ($now_str) {
            return $item_race->race_time >= $now_str;
        })
            ->order('race_time', 'asc');

        $list_has = $list_race->filter(function ($item_race) use ($now_str) {

            return $item_race->race_time < $now_str;
        })
            ->order('race_time', 'asc');

        $list = $list_wait->merge($list_has);

        return $list;
    }

    public function list_rank()
    {
        $list_rank = ZsBallRank::with('memberUser')
            ->order('num', 'desc')
            ->order('id', 'asc')
            ->limit(100)
            ->select();

        $rank = 0;
        $last_num = 0;
        $list = $list_rank->map(function ($item_rank) use (&$rank, &$last_num) {
            if ($item_rank->num !== $last_num) {
                ++$rank;
                $last_num = $item_rank->num;
            }
            return [
                // member_text 改成返回手机号（隐藏中间4位）
                // 'member_text' => $this->returnNickName($item_rank->memberUser->nickName),
                'member_text' => $this->returnMobile($item_rank->memberUser->mobile),
                'member_avatar' => $this->returnAvatar($item_rank->memberUser->avatarUrl),
                'num' => $item_rank->num,
                'rank' => $rank,
            ];
        });
        return jsonData(1, '成功', compact('list'));
    }

    public function quiz()
    {
        $vipcode = Request::param('vipcode');
        $race_id = Request::param('race_id');
        $integral = Request::param('integral');
        $quiz_end = Request::param('quiz_end');
        $integral = intval($integral);
        $quiz_end = intval($quiz_end);

        if (!$vipcode) {
            return jsonData(0, '竞猜用户不能为空');
        }

        if (!$integral || $integral < 10) {
            return jsonData(0, '竞猜积分不能为空');
        }

        if (!$quiz_end) {
            return jsonData(0, '竞猜结果不能为空');
        }

        $model_race = $this->getRace($race_id);
        if (!$model_race) {
            return jsonData(0, '比赛不存在');
        }

        if ($this->findRace($race_id, $vipcode)) {
            return jsonData(0, '已参与该场比赛竞猜');
        }

        if (!$this->checkStartTime($model_race['start_time'])) {
            return jsonData(0, '竞猜未开始');
        }

        if (!$this->checkEndTime($model_race['end_time'])) {
            return jsonData(0, '竞猜已结束');
        }

        $model_quiz = new ZsBallQuizze();
        $model_quiz->race_id = $race_id;
        $model_quiz->vipcode = $vipcode;
        $model_quiz->integral = $integral;
        $model_quiz->quiz_end = $quiz_end;
        $model_quiz->save();

        // 扣去用户积分
        UserService::BonusChange($vipcode, -$integral, '参与竞猜');

        $blue_name = $model_race->blueTeam->name ?? '';
        $red_name = $model_race->redTeam->name ?? '';
        $quiz_end_text = $this->raceEndText($quiz_end, $blue_name, $red_name);
        $quiz_end_team = $quiz_end_text;
        $quiz_end_text = $quiz_end_text ? '已 猜' : '';
        $data = [
            'quiz_can' => false,
            'quiz_end_text' => $quiz_end_text,
            'quiz_end_team' => $quiz_end_team,
            'quiz_integral' => $integral,
        ];
        return jsonData(1, '参与成功', compact('data'));
    }

    public function rule()
    {
        $content =<<<'EOT'
<pre style="white-space: pre-wrap;word-wrap: break-word; height: 400px;">
奖项设置：
一等奖1名：10000元
二等奖2名：1000元
三等奖3名：500元
单场猜中奖：10倍竞猜积分

竞猜方法：
会员凭积分参与，可选10-50积分参与一次。以单场比赛为例，比如对阵双方是英格兰vs德国，只有三个选项（英格兰胜，德国胜，打平），假设比赛结果是英格兰胜，竞猜英格兰胜的会员即可获得10倍竞猜积分返还，并且参与最终大奖排行榜排名。

活动细则：
1、单场比赛每位会员每人次限参与一次。
2、一二三等奖按竞猜命中次数降序排列获得，如遇积分相同则采取抽奖形式产生。淘汰赛阶段一共15场比赛，理论累计猜中排序为第一名15场，第二名14场，第三名13场，以此类推。以此为例，前三名排序即为15场、14场、13场。假设猜中15场的有3名会员，则在三人当中抽取一名最终获奖者。以此类推。如遇15场全中空缺，则由猜中14场的会员获得一等奖抽奖资格并以此类推。
3、有效竞猜时间为每场比赛开赛前10分钟。
4、老会员每拉新一名会员都可获得10积分每人次，多拉多得。
5、活动期间新会员入会即获赠100积分。
6、积分竞猜赔率为1:10。
7、一二三等奖获奖者凭本人身份证领奖（按国家相关规定扣除个人所得税），获奖金额为1卡畅玩金（可在B1-6F及异业联盟商户使用，特例除外）

颁奖时间：
2021年7月13日18:00在1卡通小程序上公示

领奖地点：
株洲王府井百货五楼客服中心
</pre>
EOT;
        $data = [
            'title' => '竞猜规则',
            'content' => $content,
        ];
        return jsonData(1, '成功', compact('data'));
    }

    public function result()
    {
        $content =<<<'EOT'
<pre style="white-space: pre-wrap;word-wrap: break-word;height: 400px;">
待公布
</pre>
EOT;
        $data = [
            'title' => '中奖结果',
            'content' => $content,
        ];
        return jsonData(1, '成功', compact('data'));
    }

    public function my()
    {
        $vipcode = Request::param('vipcode');

        $model_member = ZsMemberMeal::where('vipcode', $vipcode)->find();
        $right_num = ZsBallQuizze::where('vipcode', $vipcode)
            ->where('is_right', ZsBallQuizze::IS_RIGHT_YES)
            ->count();
        $wrong_num = ZsBallQuizze::where('vipcode', $vipcode)
            ->where('is_right', ZsBallQuizze::IS_RIGHT_NO)
            ->count();
        $info = [
            'member_text' => $this->returnNickName($model_member->nickName),
            'member_avatar' => $this->returnAvatar($model_member->avatarUrl),
            'right_num' => $right_num,
            'wrong_num' => $wrong_num,
            'invite' => $this->getUserInviteNum($vipcode),
        ];

        $raceTypeRels = ZsBallRace::raceTypeRels();
        $list_quiz = ZsBallQuizze::where('vipcode', $vipcode)
            ->with('raceModel')
            ->order('id', 'desc')
            ->select();
        $list = $list_quiz->map(function ($item_quiz) use ($raceTypeRels) {
            $item_race = $item_quiz->raceModel;

            $blue_name = $item_race->blueTeam->name;
            $red_name = $item_race->redTeam->name;

            $race_end_text = $this->raceEndText($item_race['race_end'], $blue_name, $red_name);
            $race_end_text = $race_end_text ? ('比赛结果：'.$race_end_text) : '';
            return [
                'race_type_text' => $raceTypeRels[$item_race->race_type] ?? '',
                'blue_name' => $blue_name,
                'blue_icon' => $item_race->blueTeam->icon,
                'red_name' => $red_name,
                'red_icon' => $item_race->redTeam->icon,
                'race_time_text' => $this->raceTimeText($item_race->race_time),
                'race_end_text' => $race_end_text,
                'is_right' => $item_quiz->is_right,
            ];
        });

        return jsonData(1, 'ok', compact('info', 'list'));
    }
    /**
     * 会员奖励积分统计
     */
    public function rewardIntegral()
    {
        $vipcode = Request::param('vipcode');
        return ZsBallQuizze::where('vipcode', $vipcode)->sum('reward_integral');
    }
    private function getRace($id)
    {
        return ZsBallRace::find($id);
    }

    private function findRace($race_id, $vipcode)
    {
        return ZsBallQuizze::where('race_id', $race_id)->where('vipcode', $vipcode)->find();
    }

    private function returnAvatar($avatarUrl)
    {
        return $avatarUrl && $avatarUrl !== 'undefined'
            ? $avatarUrl
            : '';
            // : '/pages/static/images/face.png';
    }

    private function returnNickName($nickName)
    {
        return $nickName && $nickName !== 'undefined'
            ? $nickName
            : '神秘用户';
    }

    private function returnMobile($mobile)
    {
        return substr($mobile, 0, 3) . '****' . substr($mobile, -4);
    }

    private function raceTimeText($race_time)
    {
        $timestamp = strtotime($race_time);
        return date('m.d', $timestamp) . '（星期' . $this->weekText($race_time) . '）' . date('H:i', $timestamp);
    }

    private function weekText($race_time)
    {
        $weekarray = ['日', '一', '二', '三', '四', '五', '六'];
        return $weekarray[date('w', strtotime($race_time))];
    }

    /**
     * 根据比赛结果返回获取文本
     */
    private function raceEndText($race_end, $blue_name, $red_name)
    {
        $race_end_text = '';
        if ($race_end === ZsBallRace::RACE_END_BLUE) {
            $race_end_text = "{$blue_name} 胜";
        } elseif ($race_end === ZsBallRace::RACE_END_RED) {
            $race_end_text = "{$red_name} 胜";
        } elseif ($race_end === ZsBallRace::RACE_END_DRAW) {
            $race_end_text = '平手';
        }
        return $race_end_text;
    }

    /**
     * 获取用户邀请的新用户数（自6月25日算起）
     **/
    private function getUserInviteNum($vipcode)
    {
        return ZsMemberMeal::where('pid', $vipcode)
            ->whereTime('create_at', '>=', '2021-06-25')
            ->count();
    }
}
